package host.springboot.framework.context.mvc.converter;

import host.springboot.framework.core.constant.PatternConstant;
import host.springboot.framework.core.util.inner.NumberUtils;
import org.jspecify.annotations.NonNull;
import org.springframework.core.convert.converter.Converter;

import java.time.Instant;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.format.DateTimeParseException;

/**
 * {@code LocalDate} 自定义转换器
 *
 * @author JiYinchuan
 * @since 1.0.0
 */
public class LocalDateConverter implements Converter<String, LocalDate> {

    @Override
    public LocalDate convert(@NonNull String source) {
        try {
            return LocalDate.parse(source, PatternConstant.Date.NORM_DATE_FORMATTER);
        } catch (DateTimeParseException e) {
            if (NumberUtils.isParsable(source)) {
                return Instant.ofEpochMilli(Long.parseLong(source)).atZone(ZoneId.systemDefault()).toLocalDate();
            }
            throw e;
        }
    }
}
